import DialogBox from "@/components/DialogBox";
import { ElForm, ElFormItem, FormInstance } from "element-plus";
import { defineComponent, PropType } from "vue";
import { SchemaItem } from "../../../JsonSchemaForm/interface";
export default defineComponent({
	props: {
		isAdd: Boolean,
		title: {
			type: String,
			default() {
				return "模型配置";
			}
		},
		detail: {
			type: Object as PropType<any>,
			default() {
				return {};
			}
		},
		schema: {
			type: Object as PropType<SchemaItem>,
			default() {
				return {};
			}
		},
		rules: {
			type: Array,
			default() {
				return [];
			}
		},
		treeData: {
			type: Array,
			default: () => {
				return [];
			}
		}
	},
	emits: ["submit"],
	setup(props, { attrs, expose, emit }) {
		const formRule = reactive<any>({});
		const ruleFormRef = ref<FormInstance>();
		const submitForm = (callback: any) => {
			ruleFormRef.value?.validate((valid: any) => {
				callback(valid);
			});
		};
		expose({ submitForm });
		onMounted(() => {
			props.rules.map((key: any) => {
				formRule[key] = [{ required: true, message: `请输入${props.schema[key].title}`, trigger: "change" }];
			});
		});

		watch(
			() => props.detail,
			() => {
				if (!props.isAdd) {
					props.detail.parent = props.detail.path?.replace(`.${props.detail.key}`, "");
				}
				if (props.detail.parent == props.detail.path) {
					props.detail.parent = undefined;
				}
			}
		);
		return () => {
			return (
				<DialogBox title={props.title} {...attrs} onConfirm={() => emit("submit")}>
					<ElForm label-width="80px" ref={ruleFormRef} model={props.detail} size="large">
						{Object.keys(props.schema).map(fieldKey => {
							{
								const item = props.schema[fieldKey] || {};
								return (
									<ElFormItem label={item.title} prop={fieldKey} rules={formRule[fieldKey]}>
										<el-input v-model={props.detail[fieldKey]} />
									</ElFormItem>
								);
							}
						})}
					</ElForm>
				</DialogBox>
			);
		};
	}
});
